# -*- coding: utf-8 -*-
#   基础表定义，针对各种类型 pc: parent,child, 各取第一的字母
#   t_baseConfig, t_baseConfigEntity
# @Time    ： 2024/4/12  14:21
# @Auther  ： 徐良
# File     :  pcWork.py
from share.bioDialog import Infomation
from share.dataFactory import SqlForSave
from share.modelFunction import getModel
from utils.baseWork import BaseWork
from share.sqlFunction import addWhereCondition_Str, getInsertSql, getInsertSqlList, getUpdateSqlListByModelFIdList, \
    getDelChildSql
from PySide6.QtWidgets import QMessageBox, QTableView


class PCWork(BaseWork):
    """
    基础表定义，针对各种类型
    """

    def __init__(self, parent=None):
        super(PCWork, self).__init__(parent)

    def doInitWork(self, msDict):
        """
        设置工作类初始化
        :return:
        """
        self.initWork(msDict)
        # 初始化本类
        self.__initBaseConfig()

    def __initBaseConfig(self):
        """
        # 基础表配置表表头初始化
        :return:
        """
        sql = "select * from t_baseConfig where FNumber='{sfnumber}'".format(sfnumber=self.msFNumber)
        self.sysBaseConfigModel = getModel(sql, self.baseDbType)

        pfid = self.sysBaseConfigModel.record(0).value('FId')
        sql = "select * from t_baseConfigEntity where FEntityId={sid} order by FXh".format(sid=str(pfid))
        self.sysBaseConfigChildModel = getModel(sql, self.baseDbType)
        self.__setSystemBaseConfigChildArr()

    # 系统表属性设置
    def __setSystemBaseConfigChildArr(self):
        """
        设置系统表属性
        :return:
        """
        # 系统表表头属性
        self.__B2_FFieldList = []
        self.__B2_FFieldNameList = []
        self.__B2_FFieldTypeList = []
        self.__B2_FAlignList = []
        self.__B2_FTableWidthList = []
        self.__B2_FTreeWidthList = []
        self.__B2_FIsEditList = []
        self.__B2_FVisibleList = []
        self.__B2_FJoinSqlList = []
        self.__B2_FWidgetList = []

        for row in range(0, self.sysBaseConfigChildModel.rowCount()):
            self.__B2_FFieldList.append(self.sysBaseConfigChildModel.record(row).value('FField'))
            self.__B2_FFieldNameList.append(self.sysBaseConfigChildModel.record(row).value('FFieldName'))
            self.__B2_FFieldTypeList.append(self.sysBaseConfigChildModel.record(row).value('FFieldType'))
            self.__B2_FAlignList.append(self.sysBaseConfigChildModel.record(row).value('FAlign'))
            self.__B2_FTableWidthList.append(self.sysBaseConfigChildModel.record(row).value('FTableWidth'))
            self.__B2_FTreeWidthList.append(self.sysBaseConfigChildModel.record(row).value('FTreeWidth'))
            self.__B2_FIsEditList.append(self.sysBaseConfigChildModel.record(row).value('FIsEdit'))
            self.__B2_FVisibleList.append(self.sysBaseConfigChildModel.record(row).value('FVisible'))
            self.__B2_FJoinSqlList.append(self.sysBaseConfigChildModel.record(row).value('FJoinSql'))
            self.__B2_FWidgetList.append(self.sysBaseConfigChildModel.record(row).value('FWidget'))

    # -----------------------------------------
    def getB1_FTableName(self):
        """
        获取t_baseConfig 符合条件的记录中的FTableName内容
        :return:
        """
        return self.sysBaseConfigModel.record(0).value('FTableName')

    def getB1_FLabelTitle(self):
        """
        获取t_baseConfig 符合条件的记录中的FLabelTitle内容
        :return:
        """
        return self.sysBaseConfigModel.record(0).value('FLabelTitle')

    def getB1_FSql(self):
        """
        获取t_baseConfig 符合条件的记录中的FTreeSql内容
        :return:
        """
        return self.sysBaseConfigModel.record(0).value('FSql')

    def getB1_FTreeSql(self):
        """
        获取t_baseConfig 符合条件的记录中的FTreeSql内容
        :return:
        """
        return self.sysBaseConfigModel.record(0).value('FTreeSql')

    # -------------------------------------------- 子表的列表    -----------------------
    def getB2_FFieldList(self):
        """
        获取系统表子表字段列表
        :return:
        """
        return self.__B2_FFieldList

    def getB2_FFieldNameList(self):
        """
        获取系统表子表字段名列表
        :return:
        """
        return self.__B2_FFieldNameList

    def getB2_FFieldTypeList(self):
        """
        获取系统表子表字段类型列表
        :return:
        """
        return self.__B2_FFieldTypeList

    def getB2_FAlignList(self):
        """
        获取系统表子表字段-对齐列表
        :return:
        """
        return self.__B2_FAlignList

    def getB2_FTableWidthList(self):
        """
        获取系统表子表字段-列宽列表
        :return:
        """
        return self.__B2_FTableWidthList

    def getB2_FTreeWidthList(self):
        """
        获取系统表子表字段-树列宽列表
        :return:
        """
        return self.__B2_FTreeWidthList

    def getB2_FIsEditList(self):
        """
        获取系统表子表字段-是否可编辑列表
        :return:
        """
        return self.__B2_FIsEditList

    def getB2_FVisibleList(self):
        """
        获取系统表子表字段-是否可见列表
        :return:
        """
        return self.__B2_FVisibleList

    def getB2_FJoinSqlList(self):
        """
        获取系统表子表字段-是否参加SQL列表
        :return:
        """
        return self.__B2_FJoinSqlList

    def getB2_FWidgetList(self):
        """
        获取系统表子表字段-是否参加SQL列表
        :return:
        """
        return self.__B2_FWidgetList

    #   **************************************  针对单表操作的功能
    def onTreeItemDBClick(self, it, col):
        """
        左树双击事件
        :param it:
        :param col:
        :return:
        """
        num = it.text(0)
        iLen = len(num)

        if self.baseDbType == 'sqlite':
            condi = "substr(fnumber,1,{l})='{sfn}'".format(l=str(iLen), sfn=num)
        else:
            condi = "left(fnumber,{l}='{sf}'".format(l=str(iLen), sfn=num)

        sql = addWhereCondition_Str(self.FSql, condi)
        self.readData(sql)

    #   ************************************ 表  增加， 插入， 删除， 保存
    def tableAdd(self):
        """
        表增加记录
        :return:
        """
        row = self.model.rowCount()
        self.model.insertRows(row, 1)

    def tableInsert(self):
        """
        表插入记录
        :return:
        """
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
            self.model.insertRows(row, 1)
        else:
            Infomation.info('请选定行')

    def tableDel(self):
        """
        表删除记录
        :return:
        """
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
            ask = Infomation.question(f"删除行号 {row + 1}的记录？")
            if ask == QMessageBox.No:
                return
            if self.model.record(row).value('FId') == '':
                self.model.removeRows(row)
            else:
                fid = self.model.record(row).value('FId')
                sql = getDelChildSql(self.FTableName, str(fid))
                sqlList = [sql]
                ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
                if ok['ret']:
                    # 重读数据
                    self.readData(self.FSql)
                    self.treeWidget.clear()
                    self.buildTree()
                    self.model.listUpdate.clear()
                    self.model.dirty = False

                    self.setToolbarSaveButton(0)  # 设置【保存按钮】
                else:
                    Infomation.info(ok['info'])

        else:
            Infomation.info('请选定行')

    def tableSave(self):
        """
        表删除记录
        :return:
        """
        fidList = list(self.model.listUpdate)
        sqlList = []
        # 处理主表
        pdic = {'tableName': self.FTableName, 'model': self.model, 'fidList':fidList,
                'fieldList': self.FFieldList, 'typeList': self.FFieldTypeList,
                'joinList': self.FJoinSqlList}

        # 处理新增记录
        newList = []
        if self.model.dirty:
            newList = getInsertSqlList(pdic)
        upList = []
        if len(fidList) > 0:
            upList = getUpdateSqlListByModelFIdList(pdic)

        sqlList.extend(newList)
        sqlList.extend(upList)
        print(sqlList)
        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readData(self.FSql)
            self.treeWidget.clear()
            self.buildTree()
            self.model.listUpdate.clear()
            self.model.dirty = False

            self.setToolbarSaveButton(0)  # 设置【保存按钮】
        else:
            Infomation.info(ok['info'])
